package com.mg.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSBuilder;
import com.aliyun.oss.OSSClientBuilder;
import com.mg.yygh.oss.service.FileService;
import com.mg.yygh.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author M_Dragon
 * @date 2022/9/19/019 10:46
 */
@Service
public class FileServiceimple implements FileService {
    @Override
    public String upload(MultipartFile file) {
        String endpoint = ConstantPropertiesUtils.ENDPOINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String secrect= ConstantPropertiesUtils.SECRECT;
        String bucketname = ConstantPropertiesUtils.BUCKETNAME;

        try {
            OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, secrect);
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid+filename;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            filename = timeUrl+"/"+filename;
            //调用方法实现上传
            oss.putObject(bucketname, filename, inputStream);
            // 关闭OSSClient。
            oss.shutdown();
            //上传之后文件路径
            // https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketname+"."+endpoint+"/"+filename;
            //返回
            return url;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
